package com.shuimo.emoswxapi.wx.controller;


import cn.hutool.json.JSONUtil;
import com.shuimo.emoswxapi.wx.common.util.R;
import com.shuimo.emoswxapi.wx.config.shiro.JwtUtil;
import com.shuimo.emoswxapi.wx.db.entity.TbUser;
import com.shuimo.emoswxapi.wx.service.UserService;
import com.shuimo.emoswxapi.wx.vo.req.RegisterForm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Api("用户模块Web接口")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${emos.jwt.cache-expire}")
    private int cacheExpire;

    @PostMapping("/register")
    @ApiOperation("注册用户")
    public R register(@Valid @RequestBody RegisterForm form) {
        log.info("注册用户:{}", JSONUtil.toJsonStr(form));
        TbUser user = userService.registerUser(form.getRegisterCode(), form.getCode(), form.getNickname(), form.getPhoto());
        String token = jwtUtil.createToken(user.getId());
        Set<String> permsSet = userService.searchUserPermissions(user.getId());
        saveCacheToken(token, user.getId());
        return R.ok("用户注册成功").put("token", token).put("permission", permsSet);
    }


    /**
     * 保存令牌
     *
     * @param token
     * @param userId
     */
    private void saveCacheToken(String token, int userId) {
        redisTemplate.opsForValue().set(token, String.valueOf(userId), cacheExpire, TimeUnit.DAYS);
    }

}
